from apps.gzde.models import GoodsCategory, Attachment
from extensions.common.base import *
from extensions.serializers import *
from extensions.exceptions import *
from apps.system.models import *
# from apps.goods.models import *
# from apps.purchase.models import *
# from apps.sales.models import *


# System
class RoleOptionSerializer(ModelSerializer):

    class Meta:
        model = Role
        fields = ['id', 'name']


class UserOptionSerializer(ModelSerializer):

    class Meta:
        model = User
        fields = ['id', 'username', 'name', 'is_active']


class OptionsSerializer(ModelSerializer):

    class Meta:
        fields = ['id', 'name']


class GoodsCategoryOptionSerializer(ModelSerializer):
    children = SerializerMethodField(read_only=True, label='子类')
    label = CharField(read_only=True, label='名称')
    value = IntegerField(read_only=True, label='ID')

    class Meta:
        model = GoodsCategory
        fields = ['label', 'value', 'children']

    def get_children(self, obj):
        """获取子类"""
        if obj.children.all().exists():
            return GoodsCategoryOptionSerializer(obj.children.order_by('sort'), many=True).data
        return None
    #将返回的数据进行处理
    def to_representation(self, instance):
        data = super().to_representation(instance)
        data['label'] = instance.name
        data['value'] = instance.id
        return data


class AttachmentOptionSerializer(ModelSerializer):
    src = CharField(read_only=True, label='资源地址')
    alt = CharField(read_only=True, label='提示')

    class Meta:
        model = Attachment
        fields = ['id', 'src', 'alt', 'name', 'type', 'file']
        # fields = '__all__'

    #将返回的数据进行处理
    def to_representation(self, instance):
        data = super().to_representation(instance)
        data['src'] = data.pop('file')
        data['alt'] = data['name']
        return data


